using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using System.Threading;
using DevComponents.DotNetBar;
using ProjectCommon;
using PPIDesktopClient.Logic;
using PPIDesktopClient.General;
using PPIDesktopClient.Entities;
using PPIMobileInterface.Entities;
using PPIMobileInterface.Logic;
using ThirdPartyLibraries.GoogleEarth.Classes;
using PPIProxy;
using PPIDesktopClient.Controls.Downloader;
using System.Drawing;
using VMind.Global;
using PPIDesktopClient.Logic;
using System.Deployment.Application;
namespace PPIDesktopClient
{
    public partial class frmMain : DevComponents.DotNetBar.Office2007RibbonForm
    {
        #region PRIVATE MEMBERS
        List<EVendor_Visit_XMissionStructure> m_VendorVisits;
        List<EUtility_QueryAsset> m_QueryAssets;
        List<EUtility_QueryAsset> m_SelectedQueryAssets;
        List<EVendor_Visit_XMissionStructure> m_queryMobile;

        List<EUtility_Polygon> m_Polygons;
        List<EUtility_Polygon> m_SelectedPolygons;

        List<EUtility_QueryPolygon> m_QueryPolygons;
        List<EUtility_QueryPolygon> m_SelectedQueryPolygons;

        List<EUtility_QueryAssetShown> m_SelectedQueryAssetsAsyn;
        LoadServerInformationAsyn m_ProcessServerInformation;

        GEManager m_GEManager;

        frmPoleEditor m_FrmPoleEditor;
        frmDownloadStats m_FrmDownloadImages;
        frmUploadStats m_FrmUploadInformation;
        frmOutbox m_FrmOutbox;
        frmUtilityEditor m_FrmUtilityEditor;
        frmDirection m_FrmDirection;
        frmKml m_FrmKML;
        private frmAssignUtility m_FrmUtilityAssign;
        private string m_CurrentMobileDatabaseConnectionString;
        private EDistancePositions m_DistancePositions;
        #endregion PRIVATE MEMBERS

        #region  FORM EVENTS
        public frmMain()
        {
            if (CheckIsInstanceAlreadyRunning())
                return;

            if (!CheckInternetConnection())
                return;

            CheckGooglEarthProcess();
            InitializeComponent();
            if (gevGooglePort.StartGoogleApplication())
            {
                gevGooglePort.Start();
                StartApplication();
            }
            else
            {
                DevComponents.DotNetBar.MessageBoxEx.Show("Google earth was not detected. Please install it", "Pole Position Desktop");
                SetupHelper.OpenInWebbrownser(Constants.K_GOOGLEEARTHWEB);
                Application.ExitThread();
                //this.Close();
            }
        }

        #region CLOSE GOOGLE EARTH --> WAIT --> CLOSE FORM
        bool m_GoogleEarthUnloaded = false;
        private void frmMain_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            this.Text = "Closing application - Unloading Google Earth...";
            CloseGoogleEarth();
        }
        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (!m_GoogleEarthUnloaded)
            {
                gevGooglePort.Unload();
                m_GoogleEarthUnloaded = true;
                this.Text = "Closing application...";
                Thread.Sleep(3000);
            }
            else
                Application.ExitThread();
        }
        private void Timer_Close_GE_Tick(object sender, EventArgs e)
        {
            if (!Convert.ToBoolean(Timer_Close_GE.Tag))
            {
                gevGooglePort.Unload();
                Timer_Close_GE.Tag = true;
                this.Text = "Closing application...";
            }
            else
                Application.ExitThread();
        }
        protected void CloseGoogleEarth()
        {
            ClearGEData();
            Timer_Close_GE.Enabled = true;
            this.Text = "Closing application - Unloading Google Earth...";
        }
        #endregion CLOSE GOOGLE EARTH --> WAIT --> CLOSE FORM

        private void btnCopyMobile_Click(object sender, EventArgs e)
        {
            frmCopyMobile _Form = new frmCopyMobile();
            _Form.ShowDialog();
            string _FolderPath = _Form.GetSDFPath();
            if (!string.IsNullOrEmpty(_FolderPath))
            {
                LoadMobileVisits(_FolderPath);
            }
        }
        private void btnNewPolygon_Click(object sender, EventArgs e)
        {
            frmPolygonEditor _Form = new frmPolygonEditor();
            if (qptPolygons.SelectedItem != null && qptPolygons.SelectedItem.Value.Substring(0, 1) == "p")
                _Form.ParentPolygonId = ConvertHelper.ToInt32(qptPolygons.SelectedItem.Value.Substring(1));
            if (_Form.ShowDialog() == DialogResult.OK)
                MessageBox.Show("Click Download Data to see changes");

        }
        private void btnEditPolygon_Click(object sender, EventArgs e)
        {
            Int32 _IdSelected = Int32.MinValue;
            if (grdPolygons.SelectedRows.Count == 1)
                _IdSelected = ConvertHelper.ToInt32(((System.Data.DataRowView)grdPolygons.SelectedRows[0].DataBoundItem)["Utility_PolygonId"]);
            else
            {
                if (qptPolygons.SelectedItem != null && qptPolygons.SelectedItem.Value.Substring(0, 1) == "p")
                    _IdSelected = ConvertHelper.ToInt32(qptPolygons.SelectedItem.Value.Substring(1));
            }
            if (_IdSelected != Int32.MinValue)
            {
                frmPolygonEditor _Form = new frmPolygonEditor();
                _Form.PolygonId = _IdSelected;
                if (_Form.ShowDialog() == DialogResult.OK)
                    MessageBox.Show("Click Download Data to see changes");
            }
        }
        private void btnDeletePolygon_Click(object sender, EventArgs e)
        {
            Int32 _IdSelected = Int32.MinValue;
            //if (TabMainContainer.SelectedTab == TabPolygons && grdPolygons.SelectedRows.Count == 1)
            //    _IdSelected = ConvertHelper.ToInt32(((System.Data.DataRowView)grdPolygons.SelectedRows[0].DataBoundItem)["Utility_PolygonId"]);
            //else if (TabMainContainer.SelectedTab == TabMainMap && qptPolygons.SelectedItem != null && qptPolygons.SelectedItem.Value.Substring(0, 1) == "p")
            //    _IdSelected = ConvertHelper.ToInt32(qptPolygons.SelectedItem.Value.Substring(1));

            if (grdPolygons.SelectedRows.Count == 1)
                _IdSelected = ConvertHelper.ToInt32(((System.Data.DataRowView)grdPolygons.SelectedRows[0].DataBoundItem)["Utility_PolygonId"]);
            else
            {
                if (qptPolygons.SelectedItem != null && qptPolygons.SelectedItem.Value.Substring(0, 1) == "p")
                    _IdSelected = ConvertHelper.ToInt32(qptPolygons.SelectedItem.Value.Substring(1));
            }

            if (_IdSelected != Int32.MinValue)
            {
                string _Message = "Are you sure you want to delete this polygon?";
                if (DevComponents.DotNetBar.MessageBoxEx.Show(_Message, "Pole Position Desktop", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    _Message = "There is at least one polygon query that will be deleted along with this polygon." + Environment.NewLine + "Do you still want to proceed?";
                    if ((!LUtility_Polygon.GetDeletesQuery(_IdSelected) || DevComponents.DotNetBar.MessageBoxEx.Show(_Message, "Pole Position Desktop", MessageBoxButtons.YesNo) == DialogResult.Yes))
                    {
                        LUtility_Polygon.Delete(_IdSelected);
                        MessageBox.Show("Click Download Data to see changes");
                    }

                }
            }
        }
        private void btnNewPolygonQuery_Click(object sender, EventArgs e)
        {
            frmPolygonQuery _Form = new frmPolygonQuery();
            if (_Form.ShowDialog() == DialogResult.OK)
                MessageBox.Show("Click Download Data to see changes");

        }
        private void btnEditPolygonQuery_Click(object sender, EventArgs e)
        {
            if (qptPolygons.SelectedItem != null && qptPolygons.SelectedItem.Value.Substring(0, 1) == "q")
            {
                frmPolygonQuery _Form = new frmPolygonQuery();
                _Form.PolygonQueryId = ConvertHelper.ToInt32(qptPolygons.SelectedItem.Value.Substring(1));
                if (_Form.ShowDialog() == DialogResult.OK)
                    MessageBox.Show("Click Download Data to see changes");
            }
        }
        private void btnDeletePolygonQuery_Click(object sender, EventArgs e)
        {
            if (qptPolygons.SelectedItem != null && qptPolygons.SelectedItem.Value.Substring(0, 1) == "q" && DevComponents.DotNetBar.MessageBoxEx.Show("Are you sure you want to delete this polygon query?", "Pole Position Desktop", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                string _PolygonId = qptPolygons.SelectedItem.Value.Substring(1);
                string _Message = "Polygon query id: " + _PolygonId + " will be deleted from server database. Are you sure you want to delete this polygon query?";
                if (MessageBox.Show(_Message, "Delete polygon query", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {
                    LUtility_QueryPolygon.Delete(ConvertHelper.ToInt32(_PolygonId));
                    MessageBox.Show("Click Download Data to see changes");
                }
            }
        }
        private void btnNewAsset_Click(object sender, EventArgs e)
        {
            if (TabMainContainer.SelectedTab == tabMobileAssets && grdMobileAssets.SelectedRows.Count > 0)
            {
                m_FrmPoleEditor.MobileDatabaseConnectionString = ((EVendor_Visit_XMissionStructure)grdMobileAssets.SelectedRows[0].DataBoundItem).ConnectionString;
            }
            m_FrmPoleEditor.Id = Int32.MinValue;
            if (m_FrmPoleEditor.ShowDialog() == DialogResult.OK)
                MessageBox.Show("Click Download Data to see changes");

        }
        private void btnEditAsset_Click(object sender, EventArgs e)
        {
            Int32 _SelectedID = Int32.MinValue;
            bool _AllowEdit = false;

            m_FrmPoleEditor.MobileAssetID = Int32.MinValue;
            m_FrmPoleEditor.MobileDatabaseConnectionString = "";
            if (TabMainContainer.SelectedTab == tabMobileAssets && grdMobileAssets.SelectedRows.Count > 0)
            {
                _SelectedID = ((EVendor_Visit_XMissionStructure)grdMobileAssets.SelectedRows[0].DataBoundItem).Id;
                m_FrmPoleEditor.MobileDatabaseConnectionString = ((EVendor_Visit_XMissionStructure)grdMobileAssets.SelectedRows[0].DataBoundItem).ConnectionString;
                m_FrmPoleEditor.MobileAssetID = _SelectedID;
                _AllowEdit = !(XMLHelper.GetDatabase(Constants.K_XmlOutboxPath, m_FrmPoleEditor.MobileDatabaseConnectionString).IsOpenedDatabase);
                if (_AllowEdit)
                {
                    if (m_FrmPoleEditor.ShowDialog() == DialogResult.OK)
                        LoadMobileVisits(m_CurrentMobileDatabaseConnectionString);
                }
                else
                {
                    //DialogResult _dialogDownloadImages = MessageBox.Show("Please donwload all images before editing the selected asset.", "Caption", MessageBoxButtons.YesNo);
                    //if (_dialogDownloadImages == DialogResult.Yes)
                    //{
                    //    EVendor_Visit_XMissionStructure tmpStructure = new EVendor_Visit_XMissionStructure(_SelectedID);
                    //    tmpStructure.Images = LVendor_Visit_XMissionStructures_Image.GetByStructure(tmpStructure.Vendor_Visit_XMissionStructureId);
                    //    crtlDownloaderSpecificImagesbyVisit.BringToFront();
                    //    crtlDownloaderSpecificImagesbyVisit.StartDownload(tmpStructure);
                    //}
                }
            }
            else if (mobileDatabaseTree1.SelectedItem != null)
            {
                if (mobileDatabaseTree1.SelectedItem != null && mobileDatabaseTree1.SelectedItem.Level > 0)
                {
                    _SelectedID = ConvertHelper.ToInt32(mobileDatabaseTree1.SelectedItem.Name);
                    m_FrmPoleEditor.MobileDatabaseConnectionString = mobileDatabaseTree1.SelectedItem.Value;
                    m_FrmPoleEditor.MobileAssetID = _SelectedID;
                    _AllowEdit = !(XMLHelper.GetDatabase(Constants.K_XmlOutboxPath, m_FrmPoleEditor.MobileDatabaseConnectionString).IsOpenedDatabase);
                    if (_AllowEdit)
                    {
                        m_FrmPoleEditor.ShowDialog();
                    }
                    else
                    {
                        MessageBox.Show("Cannot edit this database");
                    }
                }
            }
            else if (TabMainContainer.SelectedTab == tabGpsVisits)
            {
                if (gpsVisits1.SelectedRow != null)
                {
                    _SelectedID = ConvertHelper.ToInt32(gpsVisits1.SelectedRow.Row.ItemArray[0]);
                    m_FrmPoleEditor.MobileDatabaseConnectionString = "";
                    m_FrmPoleEditor.Id = _SelectedID;
                    _AllowEdit = Convert.ToBoolean(gpsVisits1.SelectedRow.Row.ItemArray[6]);
                    if (_AllowEdit)
                    {
                        try
                        {
                            m_FrmPoleEditor.ShowDialog();
                        }
                        catch(Exception ex)
                        {
                            if (DevComponents.DotNetBar.MessageBoxEx.Show(ex.Message, "Pole Position Desktop", MessageBoxButtons.RetryCancel) == DialogResult.Retry)
                            {
                                btnEditAsset_Click(this,new EventArgs());
                            }                           
                        }
                    }
                    else
                    {

                        try
                        {
                            EVendor_Visit_XMissionStructure tmpStructure = new EVendor_Visit_XMissionStructure(_SelectedID);
                            List<EVendor_Visit_XMissionStructures_Image> _tmpImages = LVendor_Visit_XMissionStructures_Image.GetByStructure(tmpStructure.Id);
                            foreach (EVendor_Visit_XMissionStructures_Image image in _tmpImages)
                            {
                                tmpStructure.Images.Add(image);
                            }
                            CTRLdownloadSpecificImages.BringToFront();
                            CTRLdownloadSpecificImages.StartDownload(tmpStructure);

                        }
                        catch (Exception ex)
                        {
                            if (DevComponents.DotNetBar.MessageBoxEx.Show(ex.Message, "Pole Position Desktop", MessageBoxButtons.RetryCancel) == DialogResult.Retry)
                            {
                                btnEditAsset_Click(this,new EventArgs());
                            } 
                            
                        }
                    }
                }
            }
            else
            {
                if (grdAsset.Datagrid.SelectedRows.Count > 0)
                {
                    _SelectedID = ConvertHelper.ToInt32(((System.Data.DataRowView)grdAsset.Datagrid.SelectedRows[0].DataBoundItem)["ID"]);
                    m_FrmUtilityEditor.Id = _SelectedID;
                    _AllowEdit = ConvertHelper.Tobool(((System.Data.DataRowView)grdAsset.Datagrid.SelectedRows[0].DataBoundItem)["EditReady"]);

                    if (_AllowEdit)
                    {
                        m_FrmUtilityEditor.ShowDialog();
                    }
                    else
                    {
                        DialogResult _dialogDownloadImages = MessageBox.Show("Please donwload all images before editing the selected asset.", "Caption", MessageBoxButtons.YesNo);
                        if (_dialogDownloadImages == DialogResult.Yes)
                        {
                            EUtility_Asset_XMissionStructure tmpStructure = new EUtility_Asset_XMissionStructure(_SelectedID);
                            tmpStructure.Images = LUtility_Asset_XMissionStructure_Image.GetUtility(tmpStructure.Id);
                            CTRLdownloadSpecificImages.BringToFront();
                            CTRLdownloadSpecificImages.StartDownload(tmpStructure);
                        }
                    }
                }
            }
            if (_SelectedID == Int32.MinValue)
            {
                MessageBox.Show("There is no asset selected from the list.");
                return;
            }
        }
        private void btnDeleteAsset_Click(object sender, EventArgs e)
        {
            Int32 _AssetID = Int32.MinValue;
            bool _AllowDelete = true;
            bool _IsUtility = false;

            if (TabMainContainer.SelectedTab == tabMobileAssets && grdMobileAssets.SelectedRows.Count > 0)
            {
                _AssetID = ((EVendor_Visit_XMissionStructure)grdMobileAssets.SelectedRows[0].DataBoundItem).Id;
                m_FrmPoleEditor.MobileDatabaseConnectionString = ((EVendor_Visit_XMissionStructure)grdMobileAssets.SelectedRows[0].DataBoundItem).ConnectionString;
                m_FrmPoleEditor.MobileAssetID = _AssetID;
                _AllowDelete = !(XMLHelper.GetDatabase(Constants.K_XmlOutboxPath, m_FrmPoleEditor.MobileDatabaseConnectionString).IsOpenedDatabase);
                _IsUtility = false;
            }
            else if (mobileDatabaseTree1.SelectedItem != null)
            {
                if (mobileDatabaseTree1.SelectedItem != null && mobileDatabaseTree1.SelectedItem.Level > 0)
                {
                    _AssetID = ConvertHelper.ToInt32(mobileDatabaseTree1.SelectedItem.Name);
                    m_FrmPoleEditor.MobileDatabaseConnectionString = mobileDatabaseTree1.SelectedItem.Value;
                    m_FrmPoleEditor.MobileAssetID = _AssetID;
                    _AllowDelete = !(XMLHelper.GetDatabase(Constants.K_XmlOutboxPath, m_FrmPoleEditor.MobileDatabaseConnectionString).IsOpenedDatabase);
                    _IsUtility = false;
                }
            }
            else if (TabMainContainer.SelectedTab == tabGpsVisits)
            {
                if (gpsVisits1.SelectedRow != null)
                {
                    _AssetID = ConvertHelper.ToInt32(gpsVisits1.SelectedRow.Row.ItemArray[0]);
                    m_FrmPoleEditor.MobileAssetID = Int32.MinValue;
                    _IsUtility = false;
                }
            }
            else
            {
                if (grdAsset.Datagrid.SelectedRows.Count > 0)
                {
                    _AssetID = ConvertHelper.ToInt32(((System.Data.DataRowView)grdAsset.Datagrid.SelectedRows[0].DataBoundItem)["ID"]);
                    _IsUtility = true;
                }
            }
            if (_AssetID == Int32.MinValue)
            {
                MessageBox.Show("There is no asset selected from the list.");
                return;
            }
            if (_AllowDelete)
            {
                string _Message = "Asset id: " + _AssetID + " will be deleted from server database. Are you sure you want to delete this asset?";
                if (MessageBox.Show(_Message, "Delete asset", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {
                    if (_IsUtility)
                    {

                        m_FrmUtilityEditor.Id = _AssetID;
                        m_FrmUtilityEditor.DeleteStructure();
                    }
                    else
                    {
                        m_FrmPoleEditor.Id = _AssetID;
                        m_FrmPoleEditor.DeleteStructure(_AssetID);

                    }
                    if (m_FrmPoleEditor.IsMobileAsset)
                    {
                        LoadMobileVisits(m_CurrentMobileDatabaseConnectionString);
                    }
                }
            }
            else
            {
                MessageBox.Show("Cannot edit this database");
            }

        }
        private void btnNewAssetQuery_Click(object sender, EventArgs e)
        {
            frmAssetQuery _Form = new frmAssetQuery();
            if (_Form.ShowDialog() == DialogResult.OK)
                MessageBox.Show("Click Download Data to see changes");
        }
        private void btnEditAssetQuery_Click(object sender, EventArgs e)
        {
            if (qatAssets.SelectedItem != null && qatAssets.SelectedItem.Value.Substring(0, 1) == "q")
            {
                frmAssetQuery _Form = new frmAssetQuery();
                _Form.QueryAssetId = ConvertHelper.ToInt32(qatAssets.SelectedItem.Value.Substring(1));
                if (_Form.ShowDialog() == DialogResult.OK)
                    MessageBox.Show("Click Download Data to see changes");
            }
        }
        private void btnDeleteAssetQuery_Click(object sender, EventArgs e)
        {
            if (qatAssets.SelectedItem != null && qatAssets.SelectedItem.Value.Substring(0, 1) == "q")
            {
                string _AssetQuery = qatAssets.SelectedItem.Value.Substring(1);
                string _Message = "Asset query id: " + _AssetQuery + " will be deleted from server database. Are you sure you want to delete this asset query?";
                if (DevComponents.DotNetBar.MessageBoxEx.Show(_Message, "Delete asset", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {
                    LUtility_QueryAsset.Delete(ConvertHelper.ToInt32(_AssetQuery));
                    MessageBox.Show("Click Download Data to see changes");
                }
            }
        }
        private void frmMain_Resize(object sender, EventArgs e)
        {
            gevGooglePort.Start();
        }
        private void splitter_SplitterMoved(object sender, SplitterEventArgs e)
        {
            gevGooglePort.Start();
        }
        #endregion  FORM EVENTS

        private void StartApplication()
        {
            try
            {
                m_GEManager = new GEManager(gevGooglePort, m_SelectedPolygons, m_SelectedQueryAssetsAsyn, m_SelectedQueryPolygons, m_queryMobile);
                m_FrmPoleEditor = new frmPoleEditor();
                m_FrmDownloadImages = new frmDownloadStats();
                m_FrmDownloadImages.FinishDownload += new EventHandler(m_FrmDownloadImages_FinishDownload);
                m_FrmUploadInformation = new frmUploadStats();
                m_FrmOutbox = new frmOutbox();
                m_FrmUtilityEditor = new frmUtilityEditor();
                m_FrmDirection = new frmDirection();
                m_FrmUtilityAssign = new frmAssignUtility();
                m_FrmKML = new frmKml();


                //Use to fix panel size
                TabMainContainer.SelectedPanel = tabControlPanel2;
                TabMainContainer.SelectedPanel = tabControlPanel1;
                nvTree.Hide();
                nvTree.Show();


                //CheckGooglEarthProcess(); 

                //m_ProcessServerInformation = new LoadServerInformationAsyn();
                //m_ProcessServerInformation.FinishLoadInformation += new EventHandler(m_ProcessServerInformation_FinishLoadInformation);


                SetupHelper.CreateSystemFolders();

                XMLHelper.CreateXML(Constants.K_XmlOutboxPath);
                m_SelectedQueryAssets = new List<EUtility_QueryAsset>();
                m_SelectedPolygons = new List<EUtility_Polygon>();
                m_SelectedQueryPolygons = new List<EUtility_QueryPolygon>();
                m_queryMobile = new List<EVendor_Visit_XMissionStructure>();

                m_SelectedQueryAssetsAsyn = new List<EUtility_QueryAssetShown>();
                grdAsset.QueryAssetsToShown = m_SelectedQueryAssetsAsyn;

                //LoadServerInformation();
                grdPolygons.DataSource = LUtility_Polygon.SelectAllView();
                gpsVisits1.LoadData();
                


            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmMain.StartApplication()", ex.Source, ex.Message, ex.StackTrace);
            }
        }

        void m_ProcessServerInformation_FinishLoadInformation(object sender, EventArgs e)
        {
            try
            {
                UpdateQueryAssetTree();
                UpdateQueryPolygonTree();

            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmMain.m_ProcessServerInformation_FinishLoadInformation()", ex.Source, ex.Message, ex.StackTrace);
            }
        }

        private void LoadServerInformation()
        {
            try
            {
                m_ProcessServerInformation.StartDownload();
                grdPolygons.DataSource = LUtility_Polygon.SelectAllView();
                gpsVisits1.LoadData();

            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmMain.LoadServerInformation()", ex.Source, ex.Message, ex.StackTrace);
            }
        }
        private void Timer_Internet_Connection_Tick(object sender, EventArgs e)
        {
            //CHECK IF INTERNET CONNECTION IS AVAILABLE EVERY 30 SECs
            CheckInternetConnection();
        }
        private bool CheckInternetConnection()
        {
            try
            {
                System.Net.IPHostEntry objIPHE = System.Net.Dns.GetHostByName("www.dev-poleposition.com");
                return true;
            }
            catch
            {
                // host not reachable.--> ALERT + CLOSE APPLICATION
                if (DevComponents.DotNetBar.MessageBoxEx.Show("Internet connection not available. Click Retry to check internet connection or Cancel to close application.", "Pole Position Desktop", MessageBoxButtons.RetryCancel) == DialogResult.Retry)
                {
                    return CheckInternetConnection();
                }
                else
                {
                    this.Close();
                    Application.ExitThread();
                    return false;
                }
            }
        }
        private bool CheckIsInstanceAlreadyRunning()
        {
            if (SingleApplication.Run())
            {
                return false;
            }
            else
            {
                DevComponents.DotNetBar.MessageBoxEx.Show("One instance of the application is already running.", "Pole Position Desktop", MessageBoxButtons.OK);
                this.Close();
                Application.ExitThread();
                return true;
            }
        }
        private void CheckGooglEarthProcess()
        {
            bool _Result = false;
            string _ProcessName = "googleearth";
            string _Message = "Google earth is currently running on your computer. Click OK to close Google Earth.";
            while (ProcessHelper.IsRunning(_ProcessName))
            {
                if (DevComponents.DotNetBar.MessageBoxEx.Show(_Message, "Pole Position Desktop", MessageBoxButtons.OK) == DialogResult.OK)
                {
                    try
                    {
                        _Result = ProcessHelper.KillProcess(_ProcessName);
                    }
                    catch (Exception ex)
                    {
                        return;
                    }
                }
            }
        }
        private void LoadMobileVisits(string FolderPath)
        {
            try
            {
                m_queryMobile.Clear();
                btnMobilePanel.Enabled = true;
                tabMobileAssets.Visible = true;
                m_CurrentMobileDatabaseConnectionString = FolderPath;
                List<EVisit> _MobileVisits = LogicLayer.LoadAllCompleteVisits(FolderPath);
                m_VendorVisits = LVendor_Visit_XMissionStructure.GetListFromMobileVisits(_MobileVisits);

                XMLHelper.CreateXML(Constants.K_XmlOutboxPath);
                m_queryMobile = new List<EVendor_Visit_XMissionStructure>();
                mobileDatabaseTree1.ConnectionString = FolderPath;
                mobileDatabaseTree1.Refresh();

                grdMobileAssets.DataSource = m_VendorVisits;
                lblVersionDatabaseValue.Text = LogicLayer.GetSettings(m_CurrentMobileDatabaseConnectionString).DatabaseVersion;
                lblLocationValue.Text = m_CurrentMobileDatabaseConnectionString;
                ConfigAssetMobileGrid();
                ClearGEData();
            }
            catch (Exception ex)
            {
                ErrorManager.Log("LoadMobileVisits(" + FolderPath + ")", ex.Source, ex.Message, ex.StackTrace);
            }

        }

        #region Controls


        #region QueryPolygonTree
        private void UpdateQueryPolygonTree()
        {
            try
            {
                qptPolygons.Polygons = m_ProcessServerInformation.Polygons;
                qptPolygons.QueryPolygons = m_ProcessServerInformation.QueryPolygons;
                qptPolygons.QueryTypes = new List<EUtility_Query_Type>();
                foreach (DataRow _Dr in LUtility_Query_Type.SelectAllIdName().Rows)
                    qptPolygons.QueryTypes.Add(new EUtility_Query_Type(ConvertHelper.ToInt32(_Dr["Utility_Query_TypeId"]), ConvertHelper.Tostring(_Dr["Name"])));
                qptPolygons.Refresh();

            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmMain.UpdateQueryPolygonTree()", ex.Source, ex.Message, ex.StackTrace);
            }
        }
        void qptPolygons_CheckedChange(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (sender is EUtility_Polygon)
                {
                    EUtility_Polygon polygon = (EUtility_Polygon)sender;
                    if (e.Node.Checked)
                    {
                        if (!m_SelectedPolygons.Contains(polygon))
                        {
                            polygon.Utility_Polygon_Points = LUtility_Polygon_Point.SelectAllByPolygon2(polygon.Utility_PolygonId);
                            m_SelectedPolygons.Add(polygon);
                        }
                    }
                    else if (m_SelectedPolygons.Contains(polygon))
                    {
                        m_SelectedPolygons.Remove(polygon);
                    }
                }
                else if (sender is EUtility_QueryPolygon)
                {
                    EUtility_QueryPolygon queryPolygon = (EUtility_QueryPolygon)sender;
                    if (e.Node.Checked)
                    {
                        if (!m_SelectedQueryPolygons.Contains(queryPolygon))
                        {
                            queryPolygon.Utility_Polygons = LUtility_QueryPolygon.Execute(queryPolygon.Utility_QueryPolygonId).ToArray();
                            m_SelectedQueryPolygons.Add(queryPolygon);
                        }
                    }
                    else if (m_SelectedQueryPolygons.Contains(queryPolygon))
                    {
                        m_SelectedQueryPolygons.Remove(queryPolygon);
                    }

                }
                //It could also be a query type, but we aren't interested in them (at least for now)
            }
            catch (Exception ex)
            {
                ErrorManager.Log("qptPolygons_CheckedChange()", ex.Source, ex.Message, ex.StackTrace);
            }
        }
        private void qptPolygons_SelectedQuery(object sender, EventArgs e)
        {
            btnEditPolygonQuery.Enabled = true;
            btnDeletePolygonQuery.Enabled = true;

        }
        private void qptPolygons_DeselectedQuery(object sender, EventArgs e)
        {
            btnEditPolygonQuery.Enabled = false;
            btnDeletePolygonQuery.Enabled = false;

        }
        #endregion

        #region QueryAssetTree
        private void UpdateQueryAssetTree()
        {
            try
            {
                grdAsset.Clean();
                m_SelectedQueryAssets = new List<EUtility_QueryAsset>();
                qatAssets.QueryAssets = m_ProcessServerInformation.QueryAssets;
                qatAssets.QueryTypes = new List<EUtility_Query_Type>();
                foreach (DataRow _Dr in LUtility_Query_Type.SelectAllIdName().Rows)
                    qatAssets.QueryTypes.Add(new EUtility_Query_Type(ConvertHelper.ToInt32(_Dr["Utility_Query_TypeId"]), ConvertHelper.Tostring(_Dr["Name"])));
                qatAssets.Refresh();

            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmMain.UpdateQueryAssetTree()", ex.Source, ex.Message, ex.StackTrace);
            }
        }
        void qatAssets_CheckedChange(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (sender is EUtility_QueryAsset)
                {
                    EUtility_QueryAsset queryAsset = (EUtility_QueryAsset)sender;
                    if (e.Node.Checked)
                    {
                        if (!m_SelectedQueryAssets.Contains(queryAsset))
                        {
                            m_SelectedQueryAssets.Add(queryAsset);
                            EUtility_QueryAssetShown.Add(m_SelectedQueryAssetsAsyn, queryAsset.Utility_QueryAssetId, queryAsset.Color, queryAsset.TextToShow);
                            grdAsset.ReloadAsyn();
                        }
                    }
                    else if (m_SelectedQueryAssets.Contains(queryAsset))
                    {
                        m_SelectedQueryAssets.Remove(queryAsset);
                        EUtility_QueryAssetShown.RemoveByQueryAssetId(m_SelectedQueryAssetsAsyn, queryAsset.Utility_QueryAssetId);
                        grdAsset.Reload();
                    }

                }
                //It could also be a query type, but we aren't interested in them (at least for now)
            }
            catch (Exception ex)
            {
                ErrorManager.Log("qatAssets_CheckedChange()", ex.Source, ex.Message, ex.StackTrace);
            }
        }
        private void qatAssets_SelectedNode(object sender, EventArgs e)
        {
            btnEditAssetQuery.Enabled = true;
            btnDeleteAssetQuery.Enabled = true;
        }
        private void qatAssets_DeselectedNode(object sender, EventArgs e)
        {
            btnEditAssetQuery.Enabled = false;
            btnDeleteAssetQuery.Enabled = false;
        }
        #endregion

        #region Grid Polygons
        private void grdPolygons_Leave(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection _selectedRows = grdPolygons.SelectedRows;
            foreach (DataGridViewRow r in _selectedRows)
            {
                r.Selected = false;
            }
        }
        #endregion

        #region MobileTree
        private void mobileDatabaseTree1_CheckedChange(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (sender is EVendor_Visit_XMissionStructure)
                {
                    EVendor_Visit_XMissionStructure mobileAsset = (EVendor_Visit_XMissionStructure)sender;
                    if (e.Node.Checked)
                    {
                        if (!m_queryMobile.Contains(mobileAsset))
                        {
                            m_queryMobile.Add(mobileAsset);
                        }
                    }
                    else if (m_queryMobile.Contains(mobileAsset))
                    {
                        m_queryMobile.Remove(mobileAsset);
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("mobileDatabaseTree1_CheckedChange()", ex.Source, ex.Message, ex.StackTrace);
            }
        }

        private void mobileDatabaseTree1_Enter(object sender, EventArgs e)
        {
            grdAsset.DeselectRows();
        }

        private void mobileDatabaseTree1_DeselectedNode(object sender, EventArgs e)
        {

        }

        #endregion

        #endregion

        private void ConfigAssetMobileGrid()
        {
            for (int i = 0; i < grdMobileAssets.Columns.Count; i++)
            {
                grdMobileAssets.Columns[i].Visible = false;
            }
            grdMobileAssets.Columns[11].HeaderText = "Visit ID";
            grdMobileAssets.Columns[11].Visible = true;

            grdMobileAssets.Columns[24].HeaderText = "Latitude";
            grdMobileAssets.Columns[24].Visible = true;

            grdMobileAssets.Columns[25].HeaderText = "Longitude";
            grdMobileAssets.Columns[25].Visible = true;

            grdMobileAssets.Columns[26].HeaderText = "Altitude";
            grdMobileAssets.Columns[26].Visible = true;

            grdMobileAssets.Columns[27].HeaderText = "Satellites";
            grdMobileAssets.Columns[27].Visible = true;

            grdMobileAssets.Columns[20].HeaderText = "Time";
            grdMobileAssets.Columns[20].Visible = true;

            grdMobileAssets.Columns[8].HeaderText = "Project Title";
            grdMobileAssets.Columns[8].Visible = true;

            grdMobileAssets.Columns[9].HeaderText = "Vendor Contact";
            grdMobileAssets.Columns[9].Visible = true;

            grdMobileAssets.Columns[10].HeaderText = "Type";
            grdMobileAssets.Columns[10].Visible = true;
        }

        private void LoadPolygons()
        {
            try
            {
                m_Polygons = new List<EUtility_Polygon>();
                foreach (DataRow _Dr in LUtility_Polygon.SelectAll().Rows)
                {
                    EUtility_Polygon _Polygon = new EUtility_Polygon(ConvertHelper.ToInt32(_Dr["Utility_PolygonId"]), ConvertHelper.Tostring(_Dr["Name"]), new EUtility_Polygon(ConvertHelper.ToInt32(_Dr["Utility_Polygon_ParentPolygonFk"])));
                    _Polygon.LineColor = ConvertHelper.ToInt32(_Dr["LineColor"]);
                    _Polygon.LineWidth = ConvertHelper.ToInt32(_Dr["LineWidth"]);
                    _Polygon.FillColor = ConvertHelper.ToInt32(_Dr["FillColor"]);
                    _Polygon.Name = ConvertHelper.Tostring(_Dr["Name"]);
                    m_Polygons.Add(_Polygon);
                }
                m_QueryPolygons = new List<EUtility_QueryPolygon>();
                foreach (DataRow _Dr in LUtility_QueryPolygon.SelectAll().Rows)
                    m_QueryPolygons.Add(new EUtility_QueryPolygon(ConvertHelper.ToInt32(_Dr["Utility_QueryPolygonId"]), ConvertHelper.Tostring(_Dr["Name"]), new EUtility_Query_Type(ConvertHelper.ToInt32(_Dr["Utility_Query_TypeFk"]))));
                UpdateQueryPolygonTree();
            }
            catch (Exception ex)
            {
                ErrorManager.Log("LoadPolygons()", ex.Source, ex.Message, ex.StackTrace);
            }
        }

        private void btnDownloadData_Click(object sender, EventArgs e)
        {

            try
            {
                m_FrmDownloadImages.ShowDialog();
                m_GEManager.CleanKML();
                LoadServerInformation();

            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmMain.btnDownloadData_Click()", ex.Source, ex.Message, ex.StackTrace);
            }
        }

        private void btnUploadData_Click(object sender, EventArgs e)
        {
            try
            {
                m_FrmUploadInformation.OpenedDatabaseConnectionString = m_CurrentMobileDatabaseConnectionString;
                DialogResult _resultForm = m_FrmUploadInformation.ShowDialog();
                if (_resultForm == DialogResult.OK)
                {
                    DialogResult _DialogResult = MessageBox.Show("Download Now?", "Download", MessageBoxButtons.YesNo);
                    if (_DialogResult == DialogResult.Yes)
                    {
                        LoadServerInformation();
                    }

                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmMain.btnUploadData_Click()", ex.Source, ex.Message, ex.StackTrace);
            }

        }

        protected void ClearGEData()
        {
            string _EmptyKML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://earth.google.com/kml/2.1\"></kml>";
            GEHelper.WriteKMLFile(_EmptyKML, Constants.k_Filename);
        }

        private void btnSystemSettings_Click(object sender, EventArgs e)
        {
            try
            {
                frmSettingMobile _frmSettingMobile = new frmSettingMobile();
                _frmSettingMobile.ShowDialog();

            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmMain.btnSystemSettings_Click()", ex.Source, ex.Message, ex.StackTrace);
            }
        }

        private void ShowInMap()
        {
            try
            {
                m_GEManager.M_showPolygons = chkShowPolygons.Checked;
                m_GEManager.M_showAssets = chkShowAssets.Checked;
                m_GEManager.M_queryMobile = m_queryMobile;

                m_GEManager.DistancePositions = m_DistancePositions;
                m_GEManager.ExecuteKML();
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmMain.ShowInMap()", ex.Source, ex.Message, ex.StackTrace);
                throw;
            }
        }

        private void btnCloseMobileConnection_Click(object sender, EventArgs e)
        {
            m_CurrentMobileDatabaseConnectionString = null;
            tabMobileAssets.Visible = false;
            btnMobilePanel.Enabled = false;
            nvbtnAssets.RaiseClick();
            m_queryMobile.Clear();
            m_GEManager.CleanKML();
        }

        private void btnResetMapView_Click(object sender, EventArgs e)
        {
            try
            {
                TabMainContainer.SelectedTab = TabMainMap;
                ShowInMap();
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmMain.btnResetMapView_Click()", ex.Source, ex.Message, ex.StackTrace);
            }
        }

        private void crtlDownloaderSpecificImagesbyVisit_FinishedUpload_1(object sender, CompletedEventArgs e)
        {
            try
            {
                grdAsset.UpdateValueAllowEdit(e.StructureID);
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmMain.crtlDownloaderSpecificImagesbyVisit_FinishedUpload_1()", ex.Source, ex.Message, ex.StackTrace);
            }
        }

        private void grdAsset_FinishLoadData(object sender, EventArgs e)
        {
            //TODO Alert
        }

        private void TabMainContainer_SelectedTabChanged(object sender, DevComponents.DotNetBar.TabStripTabChangedEventArgs e)
        {
            try
            {
                if (TabMainContainer.SelectedTab != tabMobileAssets && TabMainContainer.SelectedTab != tabGpsVisits)
                {
                    foreach (Control tb in TabMainContainer.Controls)
                    {
                        tb.Controls.Remove(this.nvTree);
                        tb.Controls.Remove(this.splitter);
                    }
                    TabMainContainer.SelectedPanel.Controls.Add(this.splitter);
                    TabMainContainer.SelectedPanel.Controls.Add(this.nvTree);
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmMain.TabMainContainer_SelectedTabChanged()", ex.Source, ex.Message, ex.StackTrace);
            }

        }

        private void btnLocalDatabases_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_CurrentMobileDatabaseConnectionString == null)
                {
                    m_FrmOutbox.ShowDialog();
                    if (m_FrmOutbox.DialogResult == DialogResult.OK)
                        LoadMobileVisits(m_FrmOutbox.ConnectionString);

                }
                else
                {
                    MessageBox.Show("Please close another mobile databases.");
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("Exception", "frmMain.btnLocalDatabases_Click() " + ex.Source, ex.Message, ex.StackTrace);
                throw;
            }

        }

        void m_FrmDownloadImages_FinishDownload(object sender, EventArgs e)
        {
            lblBottonMessage.Visible = true;
            lblBottonMessage.Text = "Download completed";
            Timer_ShowMessage.Start();
        }

        private void Timer_ShowMessage_Tick(object sender, EventArgs e)
        {
            Timer_ShowMessage.Stop();
            lblBottonMessage.Visible = false;
        }

        private void gpsVisits1_SearchNear(object sender, PPIDesktopClient.Events.SearchEventArgs e)
        {
            ClearGEData();
            EUtility_Asset_Shown _assetsShown = new EUtility_Asset_Shown(LVendor_Visit_XMissionStructure.GetStructure(e.Id), LUtility_Asset_XMissionStructure.SelectUtilityNearVendor(e.Id, Constants.K_FEETDISTANCE));
            m_GEManager.M_showAssets = chkShowAssets.Checked;
            m_GEManager.UtilityAssets = _assetsShown;
            m_GEManager.ExecuteUtilityKML();
            TabMainContainer.SelectedTab = TabMainMap;

        }

        private void grdAsset_ClickedShowNear(object sender, EventArgs e)
        {
            EBaseAsset _selectedAsset = new EBaseAsset();
            _selectedAsset.Id = ConvertHelper.ToInt32(((System.Data.DataRowView)grdAsset.Datagrid.SelectedRows[0].DataBoundItem)["ID"]);
            _selectedAsset.Longitude = ConvertHelper.Todouble(((System.Data.DataRowView)grdAsset.Datagrid.SelectedRows[0].DataBoundItem)["Longitude"]);
            _selectedAsset.Latitude = ConvertHelper.Todouble(((System.Data.DataRowView)grdAsset.Datagrid.SelectedRows[0].DataBoundItem)["Latitude"]);
            m_FrmDirection.SelectedAsset = _selectedAsset;

            foreach (DataGridViewRow r in gpsVisits1.DataGrid.Rows)
            {
                EBaseAsset _baseAsset = new EBaseAsset();
                _baseAsset.Id = ConvertHelper.ToInt32(((System.Data.DataRowView)r.DataBoundItem)["ID"]);
                _baseAsset.Longitude = ConvertHelper.Todouble(((System.Data.DataRowView)r.DataBoundItem)["Longitude"]);
                _baseAsset.Latitude = ConvertHelper.Todouble(((System.Data.DataRowView)r.DataBoundItem)["Latitude"]);
                if (_selectedAsset.Id != _baseAsset.Id)
                    m_FrmDirection.AddAsset(_baseAsset);
            }
            if (m_FrmDirection.ShowDialog() == DialogResult.OK)
            {
                m_DistancePositions = m_FrmDirection.SelectedPositions;
            }
            else
            {
                m_DistancePositions = new EDistancePositions();
            }
            ShowInMap();
        }

        private void gpsVisits1_AssignUtility(object sender, PPIDesktopClient.Events.SearchEventArgs e)
        {
            m_FrmUtilityAssign.SelectedVendorId = e.Id;
            if (m_FrmUtilityAssign.ShowDialog() == DialogResult.OK)
            {
                gpsVisits1.HideRow(e.Id);
            }
        }

        private void btiDownUpKml_Click(object sender, EventArgs e)
        {
            m_FrmKML.ShowDialog();
        }

        private void btiGpsProject_Click(object sender, EventArgs e)
        {
            List<EVendor_Visit_XMissionStructure> visits = LVendor_Visit_XMissionStructure.GetServerVisits();
            m_GEManager.ExecuteGPSProject(visits);
            TabMainContainer.SelectedTab = TabMainMap;
        }

        private void tabControlPanel1_Resize(object sender, EventArgs e)
        {
            gevGooglePort.GoogleEarth_Resize(tabControlPanel1.Width, tabControlPanel1.Height);
        }

        private void nvTree_Resize(object sender, EventArgs e)
        {
            gevGooglePort.GoogleEarth_Resize(tabControlPanel1.Width - nvTree.Width, tabControlPanel1.Height);
            
        }

        private void CTRLdownloadSpecificImages_FinishedUpload(object sender, CompletedEventArgs e)
        {
            gpsVisits1.UpdateValueAllowEdit(e.StructureID);
            m_FrmPoleEditor.MobileDatabaseConnectionString = "";
            m_FrmPoleEditor.Id = e.StructureID;
            try
            {
                m_FrmPoleEditor.ShowDialog();
            }
            catch (Exception ex)
            {
                if (DevComponents.DotNetBar.MessageBoxEx.Show(ex.Message, "Pole Position Desktop", MessageBoxButtons.RetryCancel) == DialogResult.Retry)
                {
                    btnEditAsset_Click(this, new EventArgs());
                }
            }
            


        }

        private void gpsVisits1_ViewOnMap(object sender, PPIDesktopClient.Events.SearchEventArgs e)
        {
            m_GEManager.SingleVisit = LVendor_Visit_XMissionStructure.GetStructure(e.Id);
            m_GEManager.ExecuteSingleKML();
            TabMainContainer.SelectedTab = TabMainMap;
        }
    }
}
